const config = require('../../config/index')
const { wxRequest } = require('../../utils/util')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    loading: false,
    baseUrl: config.baseUrl, 
    theme: wx.getStorageSync('InvoiceLoanTheme') || ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.fetchData()
    this.setData({
      theme: wx.getStorageSync('InvoiceLoanTheme') || ''
    })
  },
  fetchData(){
    const that = this
    that.setData({
      loading: true
    })
    wxRequest({
      url: `${config.baseUrl}/apply/list`,
      success(res){
        that.setData({
          list: res.data.data.map(item=>{
            const appTerm = item.appTerm
            const year = appTerm.slice(0,2)
            const month = appTerm.slice(2,4)
            return {
              ...item,
              appDt: item.appDt.replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3"),
              appTerm: Number(year)*12 + Number(month)
            }
          }) || []
        })
      },
      complete(){
        that.setData({
          loading: false
        })
      },
      invalidCb(){
        that.fetchData()
      }
    })
  },
  handleToDetail(e){
    const { appSeqno,appType,appDt,appTerm,aprvdAmt,dealStatCdDesc,dealStatCd,licenseCode,busiName } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/myApplication/index?licenseCode=${licenseCode}&busiName=${busiName}&appSeqno=${appSeqno}&appType=${appType}&appDt=${appDt}&appTerm=${appTerm}&aprvdAmt=${aprvdAmt}&dealStatCdDesc=${dealStatCdDesc}&dealStatCd=${dealStatCd}`,
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if(this.data.loading) return
    this.fetchData()
    wx.stopPullDownRefresh()
  },
})